import express from "express";
import mongoose from "mongoose";
import bodyParser from "body-parser";
import uploadFiles from "./uploadFiles/huoShan.js";
import User from "./user/model.js";
import userRouter from "./user/routes.js";
import homeApprovalRouter from "./approvalHome/routes.js";
import approveBook from "./approveBook/routes.js";
import approveCharactersRouter from "./approveCharacters/routes.js";
import homeDataRouter from "./homeData/routes.js";
import bookDataRouter from "./bookData/routes.js";
import charactersDataRouter from "./charactersData/routes.js";
import pageAssetsRouter from "./pageAssets/routes.js";
import videoDataRouter from "./videoData/routes.js";
import AnnouncementDataRouter from "./announcementData/routes.js";
import cors from "cors";
const app = express();
const PORT = 3000;
// 连接 MongoDB
const MONGO_URI = "mongodb://localhost:27017/fenghuawuque";
mongoose
  .connect(MONGO_URI, {
    useNewUrlParser: true,
    useUnifiedTopology: true,
  })
  .then(() => console.log("MongoDB connected"))
  .catch((err) => console.error("MongoDB connection error:", err));
mongoose.connection.once("open", async () => {
  const userCount = await User.countDocuments();
  if (userCount === 0) {
    await User.create({
      account: "admin",
      password: "123456",
      name: "峰伈",
      position: "社长",
    });
  }
});
//开启跨域
app.use(cors());
//添加解析工具
app.use(bodyParser.json());
// 上传文件相关接口
app.use("/upload", uploadFiles);
// 用户相关接口
app.use("/api/user", userRouter);
// 首页审批相关接口
app.use("/api/homeApproval", homeApprovalRouter);
// 书本审批相关接口
app.use("/api/approveBook", approveBook);
// 角色审批相关接口
app.use("/api/approveCharacters", approveCharactersRouter);
// 首页数据相关接口
app.use("/api/homeData", homeDataRouter);
// 书本数据相关接口
app.use("/api/bookData", bookDataRouter);
// 角色数据相关接口
app.use("/api/charactersData", charactersDataRouter);
// 其他素材数据相关接口
app.use("/api/pageAssets", pageAssetsRouter);
// 视频数据相关接口
app.use("/api/videoData", videoDataRouter);
// 公告数据相关接口
app.use("/api/announcementData", AnnouncementDataRouter);
// 测试 API
app.get("/api/hello", (req, res) => {
  res.json({ message: "Hello from Node + MongoDB server!" });
});

app.listen(PORT, "0.0.0.0", () => {
  console.log(`服务器启动成功: http://"0.0.0.0":${PORT}`);
});
